<template>
  <div class="upload-container">
    <el-upload
      ref="uploadRef"
      action=""
      :http-request="customUpload"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-error="handleError"
      :limit="1"
      :file-list="fileList"
      drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">
        拖拽文件到此处或 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持任意格式文件，单个文件大小不超过20MB
        </div>
      </template>
    </el-upload>
    
    <div class="description-input">
      <el-form :model="uploadForm" label-position="top">
        <el-form-item label="附件描述" prop="description">
          <el-input 
            v-model="uploadForm.description" 
            placeholder="请输入附件描述（选填）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    
    <div class="upload-actions">
      <el-button 
        type="primary" 
        :disabled="!uploadForm.file" 
        :loading="uploading" 
        @click="submitUpload"
      >
        上传
      </el-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import attachmentApi from '@/api/attachmentApi'
import { contractAPI } from '@/api'

export default {
  name: 'AttachmentUploader',
  components: {
    UploadFilled
  },
  props: {
    module: {
      type: String,
      required: true
    },
    moduleId: {
      type: [Number, String],
      required: true
    }
  },
  emits: ['upload-success'],
  setup(props, { emit }) {
    const uploadRef = ref(null)
    const fileList = ref([])
    const uploading = ref(false)
    const uploadForm = reactive({
      file: null,
      description: ''
    })
    // 自定义上传方法
    const customUpload = (options) => {
      uploadForm.file = options.file
      fileList.value = [{
        name: options.file.name,
        size: options.file.size,
        status: 'ready'
      }]
      return { abort: () => {} }
    }
    const beforeUpload = (file) => {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        ElMessage.error('文件大小不能超过20MB!')
        return false
      }
      return true
    }
    const handleExceed = () => {
      ElMessage.warning('一次只能上传一个文件，请先删除当前文件再上传新文件')
    }
    const handleError = () => {
      ElMessage.error('文件上传失败，请重试')
    }
    const submitUpload = async () => {
      if (!uploadForm.file) {
        ElMessage.warning('请先选择要上传的文件')
        return
      }
      uploading.value = true
      try {
        if (props.module === 'contracts') {
          await contractAPI.addAttachment(props.moduleId, uploadForm.file, uploadForm.description)
        } else {
          await attachmentApi.upload(props.module, props.moduleId, uploadForm.file, uploadForm.description)
        }
        uploadForm.file = null
        uploadForm.description = ''
        fileList.value = []
        if (uploadRef.value) {
          uploadRef.value.clearFiles()
        }
        emit('upload-success')
      } catch (error) {
        ElMessage.error('附件上传失败，请重试')
      } finally {
        uploading.value = false
      }
    }
    return {
      uploadRef,
      fileList,
      uploadForm,
      uploading,
      customUpload,
      beforeUpload,
      handleExceed,
      handleError,
      submitUpload
    }
  }
}
</script>

<style scoped>
.upload-container {
  padding: 10px;
}

.description-input {
  margin-top: 20px;
}

.upload-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload__text) {
  margin-top: 10px;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 10px;
}
</style> 